package com.mmall.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

/**
 * 操作FastDFS的工具类
 */
public class QiniuUtils {
    private static final Logger logger = LoggerFactory.getLogger(FTPUtil.class);

    private static String AK = PropertiesUtil.getProperty("qiniu.ak");
    private static String SK = PropertiesUtil.getProperty("qiniu.sk");
    private static String BUCKET = PropertiesUtil.getProperty("qiniu.bucket");

    /**
     * 将附件信息上传到qniu操作
     *
     * @param file_buff
     * @param filename
     * @return
     * @throws Exception
     */
    public static String uploadPic(byte[] file_buff, String filename) throws Exception {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = AK;
        String secretKey = SK;
        String bucket = BUCKET;
        String key = null;
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        if (filename == null) {
            key = "IMG" + UUID.randomUUID().toString().replaceAll("-", "").toUpperCase().substring(0, 8);
        } else {
            key = filename;
        }

        byte[] uploadBytes = file_buff;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(uploadBytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }

        return key;
    }
}
